package com.beiye.drivertransport.thematic.learning.finishedfragment;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.frame.adapter.CommonAdapter;
import com.android.frame.adapter.ViewHolder;
import com.android.frame.http.HttpListener;
import com.android.frame.view.linearlistview.LinearListView;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.TakePhotoScrolls1Activity;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.DaikaoBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.MineUseBean;
import com.beiye.drivertransport.fragment.TwoBaseFgt;
import com.beiye.drivertransport.http.Course;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.thematic.learning.test.HaveTestthematiclearnActivity;
import com.beiye.drivertransport.thematic.learning.test.TestthematiclearningActivity;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import okhttp3.Call;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
//测验
public class TestthematiclearnedFragment extends TwoBaseFgt {


    TextView tv_text_learning;

    LinearListView lv_test;
    //  @Bind(R.id.tv_test2)
//  TextView tv_test2;

    RelativeLayout re_test;

    TextView tv_test3;
    private TestAdapter testAdapter;
    List<DaikaoBean.RowsBean> finishrows = new ArrayList<>();
    List<DaikaoBean.RowsBean> finishnorows = new ArrayList<>();
    List<DaikaoBean.RowsBean> newrows = new ArrayList<>();

    private int stId;
    private PopupWindow mUserOnePopWindow;
    private String userHeadImg;
    private static final int USERINFO_REQUEST = 4;
    private String adId;
    private int sn;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_testthematiclearning;
    }


    @Override
    public void onClick(View view) {

    }

    @Override
    public void initData() {
        tv_text_learning = (TextView) getActivity().findViewById(R.id.tv_text_learning);
        lv_test = (LinearListView) getActivity().findViewById(R.id.lv_test);
        re_test = (RelativeLayout) getActivity().findViewById(R.id.re_test);
        tv_test3 = (TextView) getActivity().findViewById(R.id.tv_test3);
        tv_text_learning.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String learnstr = tv_text_learning.getText().toString().trim();
                if (learnstr.equals("我知道了，申请测验")) {
                    SharedPreferences sp = getActivity().getSharedPreferences("TestthematiclearningFragment", Context.MODE_PRIVATE);
                    String orgId = sp.getString("orgId", "");
                    int stId = sp.getInt("stId", 0);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean data = userInfo.getData();
                    if (data == null) {
                        return;
                    }
                    String userId = data.getUserId();
                    showLoadingDialog("");
                    new Login().getApplyTestthematiclear(userId, orgId, stId, (HttpListener) getContext(), 1);//申请测验
                } else if (learnstr.equals("我知道了，继续测验")) {

                    showLoadingDialog("");
                    Bundle bundle = new Bundle();
                    bundle.putInt("sn", newrows.get(0).getSn());
                    //   bundle.putString("qptId", newrows.get(0).getQptId());
                    bundle.putInt("qpsn", newrows.get(0).getQpSn());
                    startActivity(TestthematiclearningActivity.class, bundle);
                }
            }
        });

        EventBus.getDefault().register(this);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("StaticData", Context.MODE_PRIVATE);
        adId = sharedPreferences.getString("adId", "");

        tv_text_learning.setVisibility(View.GONE);
        lv_test.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                if (Utils.isFastClicker()) {
                    return;
                }
                int finishMark = testAdapter.getItem(position).getFinishMark();
                if (finishMark == 1) {

                    Bundle bundle = new Bundle();
                    bundle.putInt("havesn", testAdapter.getItem(position).getSn());
                    bundle.putLong("havecreation", testAdapter.getItem(position).getCreationDate());
                    bundle.putInt("haveqpsn", testAdapter.getItem(position).getQpSn());
                    bundle.putString("haveqptName", testAdapter.getItem(position).getQptName());
                    bundle.putString("haveqpName", testAdapter.getItem(position).getQpName());
                    bundle.putInt("havetotalScore", testAdapter.getItem(position).getTotalScore());
                    bundle.putInt("havepassScore", testAdapter.getItem(position).getPassScore());
                    bundle.putInt("havescore", testAdapter.getItem(position).getScore());
                    bundle.putInt("havepassMark", testAdapter.getItem(position).getPassMark());
                    bundle.putLong("testEndDate", testAdapter.getItem(position).getTestEndDate());

                    /**
                     * 此处要传这条已考的所有数据
                     */
                    startActivity(HaveTestthematiclearnActivity.class, bundle);
                } else {
                    showLoadingDialog("");
                    Bundle bundle = new Bundle();
                    bundle.putInt("sn", testAdapter.getItem(position).getSn());
                    //  bundle.putString("qptId", testAdapter.getItem(position).getQptId());
                    bundle.putInt("qpsn", testAdapter.getItem(position).getQpSn());

                    /**
                     * 此处要传这条待考的所有数据
                     */
                    startActivity(TestthematiclearningActivity.class, bundle);

                }

            }
        });


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences sp = getActivity().getSharedPreferences("TestthematiclearningFragment", Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        int stId = sp.getInt("stId", 0);
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        showLoadingDialog("");
        new Login().getTestandexamination(userId, orgId, stId, 1, sn+"", this, 2);
    }

    @Override
    public void requestData() {

        String orgId = getArguments().getString("orgId");
        stId = getArguments().getInt("stId");
        sn=getArguments().getInt("sn");
        SharedPreferences sp = getActivity().getSharedPreferences("TestthematiclearningFragment", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putInt("stId", stId);
        edit.putString("orgId", orgId);
        edit.commit();
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        showLoadingDialog("");
        new Login().getTestandexamination(userId, orgId, stId, 1, sn+"", this, 2);
        getUserInfo();
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        super.onSuccess(result, call, response, what);
        if (what == 1)//申请测验
        {
            dismissLoadingDialog();
            SharedPreferences sp = getActivity().getSharedPreferences("TestthematiclearningFragment", Context.MODE_PRIVATE);
            String orgId = sp.getString("orgId", "");
            int stId = sp.getInt("stId", 0);
            LoginUserBean userInfo = UserManger.getUserInfo();
            LoginUserBean.DataBean data = userInfo.getData();
            String userId = data.getUserId();
            new Login().getTestandexamination(userId, orgId, stId, 1, sn+"",this, 3);//再次调列表数据接口
        } else if (what == 2) {
            dismissLoadingDialog();
            DaikaoBean daikaoBean = JSON.parseObject(result, DaikaoBean.class);
            List<DaikaoBean.RowsBean> daikaorows = daikaoBean.getRows();

            finishrows.clear();
            finishnorows.clear();
            newrows.clear();
            if (daikaorows.size() == 0) {
                re_test.setVisibility(View.GONE);
                return;
            }
            re_test.setVisibility(View.VISIBLE);
            for (int i = 0; i < daikaorows.size(); i++) {

                if (daikaorows.get(i).getFinishMark() == 1) {
                    finishrows.add(daikaorows.get(i));
                } else {
                    finishnorows.add(daikaorows.get(i));
                }
            }
            if (finishnorows.size() >= 1) {
                tv_text_learning.setEnabled(true);
                tv_text_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                tv_text_learning.setText("我知道了，继续测验");

            } else if (finishnorows.size() == 0) {
                tv_text_learning.setEnabled(true);
                tv_text_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                tv_text_learning.setText("我知道了，申请测验");
            }
            newrows.addAll(finishnorows);
            newrows.addAll(finishrows);
            testAdapter = new TestAdapter(getContext(), newrows, R.layout.testandexamiantion_item_layout2);
            lv_test.setAdapter(testAdapter);
        } else if (what == 3)//申请直接进去考试功能
        {
            DaikaoBean daikaoBean = JSON.parseObject(result, DaikaoBean.class);
            List<DaikaoBean.RowsBean> daikaorows = daikaoBean.getRows();
            finishnorows.clear();
            if (daikaorows.size() == 0) {
                showToast("未生成新模拟试卷");
                return;
            }
            for (int i = 0; i < daikaorows.size(); i++) {

                if (daikaorows.get(i).getFinishMark() != 1) {
                    finishnorows.add(daikaorows.get(i));
                }
            }
            int sn = finishnorows.get(0).getSn();
            int qpSn = finishnorows.get(0).getQpSn();
            Bundle bundle = new Bundle();
            bundle.putInt("sn", sn);
            bundle.putInt("qpsn", qpSn);
            startActivity(TestthematiclearningActivity.class, bundle);
        } else if (what == USERINFO_REQUEST) {
            MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
            MineUseBean.DataBean data = mineUseBean.getData();
            userHeadImg = data.getPhotoUrl();

            if (adId.substring(0, 2).equals("51")) { //四川地区不进行拍照
                return;
            }

            /*if(stId==700002 || stId==700003){ //两类人员人脸识别
                if(userHeadImg!=null){ //有头像拍照验证
                    showUseronePopwindow();
                }else{//没有头像，提示
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                    View view = View.inflate(getContext(), R.layout.dialog_normal_layout, null);
                    TextView tv_message= (TextView) view.findViewById(R.id.message);//输入内容
                    tv_message.setText("请先上传个人头像");
                    TextView btn_sure = (TextView) view.findViewById(R.id.positiveButton);
                    TextView btn_cancel = (TextView) view.findViewById(R.id.negativeButton);
                    btn_cancel.setVisibility(View.GONE);
                    btn_sure.setText("我知道");
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    dialog.getWindow().setContentView(view);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.setCancelable(false);
                    btn_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            getActivity().finish();
                        }
                    });
                }
            }*/
        }
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        super.onError(result, call, response, what);
        if (what == 1) {
            dismissLoadingDialog();
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            int code = checkBean.getCode();
            if (code == 1880) {
                tv_text_learning.setEnabled(false);
                tv_text_learning.setBackgroundResource(R.drawable.notestbutton);//不可点击
            } else {
                String msg = checkBean.getMsg();
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
                builder1.setMessage(msg);
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ;
                        //设置你的操作事项
                    }
                });
                builder1.create().show();
            }
        }
    }

    @Override
    public void onUserVisible() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        String imgurl = event.getMessage();
        String messageurl = event.getMessageurl();
        boolean isphoto = event.isIsphoto();
        int code = event.getCode();
        String msg = event.getMsg();
        int faceRecgMark = event.getFaceRecgMark();

        if (faceRecgMark > 0) { //人脸识别
            if (isphoto) {
                Toasty.success(getContext(), "人脸识别成功！", Toast.LENGTH_SHORT, true).show();
            } else {
                if (code == 1) {
                    showAlertDialog("非常抱歉，您还没有上传个人头像，我们无法对您对你进行人脸识别。");
                } else if (code == 2) {
                    showAlertDialog("非常抱歉。系统正在进行维护，请您稍后再进行学习。");
                } else if (code == 3) {
                    showAlertDialog("请确保拍照面部完整，五官清晰，如您多次人脸失败，请在“我的头像”中检查您的个人头像是否正常且且清晰。");
                } else {
                    showAlertDialog(msg);
                }
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }

    public class TestAdapter extends CommonAdapter<DaikaoBean.RowsBean> {
        private Context context;
        private List<DaikaoBean.RowsBean> mList;

        public TestAdapter(Context context, List<DaikaoBean.RowsBean> mList, int itemLayoutId) {
            super(context, mList, itemLayoutId);
            this.context = context;
            this.mList = mList;
        }

        @Override
        public void convert(ViewHolder holder, DaikaoBean.RowsBean item, int positon) {
            //   TextView tv_testtitle = holder.getView(R.id.tv_testtitle);//日期
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_scon = holder.getView(R.id.tv_scon1);
            TextView tv_jige = holder.getView(R.id.tv_scon2);

//   if(mList.get(0).getQpName()==null)
//   {
//     tv_test3.setText("");
//   }else{
//     tv_test3.setText(mList.get(0).getQpName());
//   }
            int finishMark = mList.get(positon).getFinishMark();
            if (finishMark == 1) {
                long creationDate = mList.get(positon).getCreationDate();
                //mill为你龙类型的时间戳
                if (creationDate > 0) {

                    Date date = new Date(creationDate);
                    String time = "";
                    try {
                        //yyyy表示年MM表示月dd表示日
                        //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        //进行格式化
                        time = sdf.format(date);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    tv_time.setText("测验时间:" + time);
                }
                int score = mList.get(positon).getScore();
                tv_scon.setText(score + "分");
                tv_scon.setTextColor(getResources().getColor(R.color.hidetroublenext));
                tv_jige.setVisibility(View.VISIBLE);
                int passMark = mList.get(positon).getPassMark();
                if (passMark == 1) {
                    tv_jige.setText("及格");
                    tv_jige.setTextColor(getResources().getColor(R.color.hiddengreen));
                } else {
                    tv_jige.setText("不及格");
                    tv_jige.setTextColor(getResources().getColor(R.color.bixue_red));
                }

            } else {
                tv_time.setText("测验时间:");
                tv_scon.setText("未完成测验");
                tv_scon.setTextColor(getResources().getColor(R.color.holetotal_red));
                tv_jige.setVisibility(View.GONE);
            }
        }
    }

    //自定义方法
    private void showUseronePopwindow() { //用户拍照弹窗
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.test_popwindowlayout, null);
        mUserOnePopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        ImageView takepciture = (ImageView) contentView.findViewById(R.id.img_photo1);//点拍照
        final LinearLayout le_takepicture = (LinearLayout) contentView.findViewById(R.id.le_takepicture1);//跟布局
        mUserOnePopWindow.setFocusable(false);
        mUserOnePopWindow.setOutsideTouchable(false);
        mUserOnePopWindow.showAtLocation(le_takepicture, Gravity.CENTER, 0, 0);

        takepciture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mUserOnePopWindow.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("photoUrl", userHeadImg);
                bundle.putInt("faceMark", 2);
                startActivityForResult(TakePhotoScrolls1Activity.class, bundle, 0);
            }
        });
    }

    private void showAlertDialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = View
                .inflate(getContext(), R.layout.diolog_learn_layout, null);
        TextView tv_message = (TextView) view
                .findViewById(R.id.message);//输入内容
        tv_message.setText(msg);
        TextView btn_sure = (TextView) view.findViewById(R.id.positiveButton);
        TextView btn_cancel = (TextView) view.findViewById(R.id.negativeButton);
        btn_cancel.setVisibility(View.GONE);
        btn_sure.setText("确定");
        AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getWindow().setContentView(view);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                showUseronePopwindow();
            }
        });
    }


    //网络请求
    private void getUserInfo() {//获取用户信息
        LoginUserBean userInfo = UserManger.getUserInfo();
        String userId = userInfo.getData().getUserId();
        new Login().getUser(userId, this, USERINFO_REQUEST);
    }
}
